<template>
  <div class="schedule-add">
    <div class="schedule-form">
      <el-form :model="form" label-width="100px">
        <div class="form-row">
          <el-form-item label="排班月份">
            <el-select v-model="form.yearMonth" placeholder="请选择月份" class="custom-select" @change="handleMonthChange"
              :disabled="true">
              <el-option v-for="item in monthOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="上/下半月">
            <el-select v-model="form.halfMonth" placeholder="请选择上/下半月" class="custom-select"
              @change="handleHalfMonthChange" :disabled="true">
              <el-option label="上半月(1-15号)" value="first" />
              <el-option label="下半月(16-月末)" value="second" />
            </el-select>
          </el-form-item>
          <el-form-item label="护士姓名">
            <el-select v-model="form.nurse" placeholder="请选择护士" class="custom-select" @change="handleNurseChange"
              :disabled="true">
              <el-option v-for="item in nurseOptions" :key="item.nurseCode" :label="item.name"
                :value="item.nurseCode" />
            </el-select>
          </el-form-item>
        </div>
      </el-form>

      <div class="schedule-grid">
        <div v-for="(day, index) in scheduleData" :key="index" class="schedule-row">
          <div class="schedule-cell">
            <div class="day-number">{{ day.number }}号</div>
            <div class="day-name">{{ day.weekday }}</div>
            <div class="shift-options">
              <el-radio-group v-model="day.shift">
                <el-radio label="早班">早班</el-radio>
                <el-radio label="中班">中班</el-radio>
                <el-radio label="晚班">晚班</el-radio>
                <el-radio label="休息">休息</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>

      <div class="form-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存修改</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import { getCurrentInstance } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

const form = reactive({
  yearMonth: '',
  halfMonth: '',
  nurse: '',
  nurseName: ''
})

const scheduleData = ref([])
const nurseOptions = ref([])
const responseData = ref([])

// 生成月份选项
const generateMonthOptions = () => {
  const options = []
  const currentDate = dayjs()

  for (let i = 0; i < 12; i++) {
    const date = currentDate.add(i, 'month')
    const value = date.format('YYYY-MM')
    const label = date.format('YYYY年MM月')
    options.push({ value, label })
  }

  return options
}

const monthOptions = generateMonthOptions()

// 获取护士列表
const getNurses = () => {
  proxy.http.get("/api/WorkforceController/GetNurseList").then(res => {
    if (!res || !res.status) {
      ElMessage.error(res?.message || '获取护士列表失败')
      nurseOptions.value = []
      return
    }
    nurseOptions.value = res.data
  }).catch(err => {
    console.error('获取护士列表错误:', err)
    ElMessage.error('获取护士列表失败：' + (err.message || '未知错误'))
    nurseOptions.value = []
  })
}

// 生成排班数据
const generateScheduleData = (yearMonth, halfMonth) => {
  if (!yearMonth || !halfMonth) return []

  const [year, month] = yearMonth.split('-')
  const daysInMonth = dayjs(`${year}-${month}`).daysInMonth()
  const scheduleData = []

  let startDay = halfMonth === 'first' ? 1 : 16
  let endDay = halfMonth === 'first' ? 15 : daysInMonth

  for (let i = startDay; i <= endDay; i++) {
    const date = dayjs(`${year}-${month}-${i}`)
    scheduleData.push({
      number: i,
      weekday: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.day()],
      shift: ''
    })
  }

  return scheduleData
}

// 获取路由参数值转换为stage
const getStageValue = (halfMonth) => {
  return halfMonth === 'first' ? 1 : 2
}

// 根据day值判断上半月还是下半月
const getHalfMonthFromDay = (day) => {
  return parseInt(day) <= 15 ? 'first' : 'second'
}

// 获取排班详情
const getScheduleDetail = async () => {
  try {
    let obj = {
      nurseCode: route.query.nurseCode || '',
      year: Number(route.query.year) || 0,
      month: Number(route.query.month) || 0,
      stage: Number(route.query.stage) || 0  // 使用从路由接收的stage参数
    }

    // 验证参数
    if (!obj.nurseCode || !obj.year || !obj.month) {
      ElMessage.warning('缺少必要的查询参数')
      router.back()
      return
    }

    console.log('获取排班详情参数:', obj)

    // 使用对象传参
    const result = await proxy.http.post("/api/WorkforceController/GetWorkforcesDetail", obj)

    if (!result || !result.status) {
      ElMessage.error(result?.message || '获取排班详情失败')
      router.back()
      return
    }

    if (!result.data || result.data.length === 0) {
      ElMessage.warning('未找到排班数据')
      return
    }

    console.log('获取到的排班详情:', result.data)

    // 保存原始数据用于后续获取ID
    responseData.value = result.data

    const firstRecord = result.data[0]
    // 构造年月格式 YYYY-MM
    form.yearMonth = `${obj.year}-${String(obj.month).padStart(2, '0')}`
    form.nurse = firstRecord.nurseCode || obj.nurseCode
    form.nurseName = firstRecord.nurseName
    
    // 设置上/下半月，根据接收到的stage参数
    if (obj.stage === 1) {
      form.halfMonth = 'first'
    } else if (obj.stage === 2) {
      form.halfMonth = 'second'
    } else {
      // 如果stage不是1或2，则根据数据中的日期判断
      const day = parseInt(firstRecord.stage)
      form.halfMonth = getHalfMonthFromDay(day)
    }
    
    // 生成日期数据
    scheduleData.value = generateScheduleData(form.yearMonth, form.halfMonth)
    
    // 填充班次数据
    result.data.forEach(item => {
      const dayIndex = scheduleData.value.findIndex(d => d.number === parseInt(item.stage))
      if (dayIndex !== -1) {
        scheduleData.value[dayIndex].shift = item.classGroup
      }
    })
  } catch (error) {
    console.error('获取排班详情失败：', error)
    ElMessage.error('获取排班详情失败：' + (error.message || '未知错误'))
    router.back()
  }
}

// 验证排班规则
const validateScheduleRules = (scheduleData) => {
  const scheduledDays = scheduleData
    .filter(day => day.shift)
    .sort((a, b) => a.number - b.number)

  if (scheduledDays.length === 0) {
    return { valid: false, message: '请至少安排一个班次' }
  }

  const weekGroups = {}
  scheduledDays.forEach(day => {
    const date = dayjs(`${form.yearMonth}-${day.number}`)
    const weekKey = date.startOf('week').format('YYYY-MM-DD')

    if (!weekGroups[weekKey]) {
      weekGroups[weekKey] = []
    }
    weekGroups[weekKey].push({
      ...day,
      date: date
    })
  })

  for (const [weekStart, days] of Object.entries(weekGroups)) {
    const hasNightShift = days.some(day => day.shift === '晚班')
    if (!hasNightShift) {
      const weekDate = dayjs(weekStart)
      return {
        valid: false,
        message: `${weekDate.format('MM.DD')}这周未安排晚班，每周必须安排一次晚班`
      }
    }
  }

  for (let i = 0; i < scheduledDays.length - 1; i++) {
    const currentDay = scheduledDays[i]
    const nextDay = scheduledDays[i + 1]

    const currentDate = dayjs(`${form.yearMonth}-${currentDay.number}`)
    const nextDate = dayjs(`${form.yearMonth}-${nextDay.number}`)
    const isConsecutiveDays = nextDate.diff(currentDate, 'day') === 1

    if (isConsecutiveDays && currentDay.shift === '晚班' && nextDay.shift === '早班') {
      return {
        valid: false,
        message: `${currentDay.number}号晚班后不能直接安排${nextDay.number}号早班`
      }
    }
  }

  return { valid: true }
}

// 提交修改
const handleSubmit = async () => {
  try {
    // 基本表单验证
    if (!form.yearMonth || !form.halfMonth || !form.nurse) {
      ElMessage.warning('请填写完整的基本信息')
      return
    }

    const validation = validateScheduleRules(scheduleData.value)
    if (!validation.valid) {
      ElMessage.warning(validation.message)
      return
    }

    const workforceData = scheduleData.value
      .filter(day => day.shift)
      .map(day => {
        // 查找对应日期的原始数据以获取ID
        const originalRecord = responseData.value.find(r => parseInt(r.stage) === day.number)
        return {
          Id: originalRecord?.id || 0, // 添加主键ID
          Year: parseInt(form.yearMonth.split('-')[0]),
          Month: parseInt(form.yearMonth.split('-')[1]),
          Stage: day.number.toString(), // Stage仍然使用日期
          NurseCode: form.nurse,
          NurseName: form.nurseName,
          WorkDate: `${form.yearMonth}-${day.number.toString().padStart(2, '0')}`,
          WorkWeek: dayjs(`${form.yearMonth}-${day.number}`).format('YYYY-MM-DD HH:mm:ss'),
          ClassGroup: day.shift,
          Creator: "当前用户名",
          CreateTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
        }
      })

    console.log('更新排班数据:', workforceData)

    const result = await proxy.http.post("/api/WorkforceController/UpdWorkforces", workforceData)
    if (!result || !result.status) {
      ElMessage.error(result?.message || '修改排班失败')
      return
    }
    
    ElMessage.success('修改排班成功')
    handleCancel()
  } catch (error) {
    console.error('修改排班出错：', error)
    ElMessage.error('修改排班失败：' + (error.message || '未知错误'))
  }
}

// 取消修改
const handleCancel = () => {
  router.back()
}

// 监听月份和上下半月变化
const handleMonthChange = () => {
  if (form.halfMonth) {
    scheduleData.value = generateScheduleData(form.yearMonth, form.halfMonth)
  }
}

const handleHalfMonthChange = () => {
  if (form.yearMonth) {
    scheduleData.value = generateScheduleData(form.yearMonth, form.halfMonth)
  }
}

// 监听护士选择变化
const handleNurseChange = (value) => {
  const nurse = nurseOptions.value.find(n => n.nurseCode === value)
  if (nurse) {
    form.nurseName = nurse.name
  }
}

onMounted(() => {
  getNurses()
  getScheduleDetail()
})
</script>

<style scoped>
.schedule-add {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.schedule-form {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.schedule-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 24px;
  padding: 20px;
  background-color: #f9fafc;
  border-radius: 8px;
}

.schedule-cell {
  background-color: #fff;
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.02);
  transition: all 0.3s ease;
}

.schedule-cell:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.05);
}

.day-number {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #303133;
}

.day-name {
  color: #606266;
  margin-bottom: 12px;
  font-size: 14px;
}

.shift-options {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.shift-options .el-radio {
  margin-right: 0;
  margin-bottom: 8px;
}

.form-footer {
  margin-top: 32px;
  display: flex;
  justify-content: center;
  gap: 24px;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
}

.form-footer .el-button {
  min-width: 120px;
  padding: 12px 30px;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  padding: 0 20px;
  margin-bottom: 20px;
}

.custom-select {
  width: 220px !important;
}

.el-form-item {
  margin-bottom: 20px;
  margin-right: 0;
}

:deep(.el-radio__label) {
  font-size: 14px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
